<template>
  <section class="component modify-client">
    <el-form
      :model="model"
      :rules="rules"
      ref="add-form"
      label-width="120px"
      class="text-left"
    >
      <div class="add-queue-title">队列信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="队列代码" prop="queueCode">
            <el-input
              v-model="model.queueCode"
               :maxlength="20"
              :disabled="queueId !== ''"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="队列名称" prop="queueName">
            <el-input
              v-model="model.queueName"
               :maxlength="20"
              :disabled="queueId !== ''"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="队列类型" prop="queueCategory">
            <el-select v-model="model.queueCategory" disabled>
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'QueueCategory'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="队列状态" prop="status">
            <el-select v-model="model.status" :disabled="readOnly">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'CommonState'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="锁定到期日期" prop="lockEndDate">
            <el-select v-model="model.lockEndDate" :disabled="readOnly">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'LockEndDate'
                )"
                :key="index"
                :label="name"
                :value="code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="['MONTH_DAY', 'MONTH'].includes(model.lockEndDate)"
        >
          <el-form-item
            :label="
              model.lockEndDate === 'MONTH'
                ? '锁定至第X个自然月'
                : '锁定至第X月'
            "
            prop="expireMonth"
          >
            <el-input
              v-model="model.expireMonth"
               :maxlength="6"
              :disabled="readOnly"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="['MONTH_DAY', 'DAY'].includes(model.lockEndDate)"
        >
          <el-form-item
            :label="
              model.lockEndDate === 'DAY' ? '锁定至第X个自然日' : '锁定至第X号'
            "
            prop="expireDay"
          >
            <el-input v-model="model.expireDay" :disabled="readOnly" :maxlength="6"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="model.lockEndDate === 'SOME'">
          <el-form-item label="锁定到某个日期" prop="expireDate">
            <el-date-picker
              :picker-options="$common.datePickDisabledDate(1)"
              placeholder="请选择日期"
              type="date"
              v-model="model.expireDate"
              value-format="yyyy-MM-dd"
              :disabled="readOnly"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="分案日期策略" prop="divisionStrategyId">
            <el-select v-model="model.divisionStrategyId" :disabled="readOnly">
              <el-option
                v-for="item in strategy"
                :key="item.id"
                :label="item.strategyName"
                :value="item.id"
                :disabled="select = item.state === 'DISABLED' ? true : false"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="calendar">
        <div
          :class="getDateClass(index)"
          v-for="(item, index) in new Date(
            new Date().getFullYear(),
            new Date().getMonth() + 1,
            0
          ).getDate()"
          :key="index"
        >
          {{ index + 1 }}
        </div>
      </el-row>
      <el-row>
        <el-form-item label="添加队列注记" prop="queueRemark">
          <el-input
            type="textarea"
            :disabled="readOnly"
            v-model="model.queueRemark"
            style="width: 505px"
            :maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-row>
      <el-row class="history-table" v-if="readOnly || edit">
        <el-form-item label="队列历史注记">
          <data-box
            :data="signHistoryPageList"
            @onPageChange="refreshSignHistoryData"
            :page="pageSignHistoryService"
          >
            <template slot="columns">
              <el-table-column
                prop="createTime"
                label="注记时间"
                :formatter="row => $filter.dateTimeFormat(row.createTime)"
                :min-width="$helper.getColumnWidth(3)"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="operatorRealName"
                label="添加人"
                :min-width="$helper.getColumnWidth(3)"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="signContent"
                label="内容"
                show-overflow-tooltip
              ></el-table-column>
            </template>
          </data-box>
        </el-form-item>
      </el-row>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="close" v-if="edit || readOnly">{{edit ? '取消' : '关闭'}}</el-button>
      <el-button @click="close" v-else>取消</el-button>
      <el-button v-if="!readOnly" @click="commit">{{
        edit ? "提交审批" : "确定"
      }}</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { QueueService } from "~/services/domain-service/queue-manage.service";
import { CaseQueueService } from "~/services/domain-service/case-queue.service";
import { PageService } from "~/utils/page.service";

@Component({
  components: {}
})
export default class AddQueue extends Vue {
  @Prop() private readOnly;
  @Prop() private edit;
  @Prop() private queueId;
  @Dependencies(QueueService)
  private queueService: QueueService;
  @Dependencies(PageService)
  private pageSignHistoryService: PageService;
  @Dependencies(CaseQueueService)
  private caseQueueService: CaseQueueService;

  private strategy: any = [];
  private signHistoryList = [];
  private signHistoryPageList = [];
  private SignHisqueueId : any = '';
  //队列实体
  private model: any = {
    queueCode: "",
    queueName: "",
    queueCategory: "ROBOT",
    status: "ENABLED",
    divisionStrategyId: "",
    strategyDate: "",
    strategyName: "",
    queueRemark: "",
    lockEndDate: "",
    expireMonth: "",
    expireDay: "",
    expireDate: "",
  };
  //数据校验
  private rules: any = {
    queueCode: [
      { required: true, message: "请输入队列代码", trigger: "blur" },
      { pattern: /^[A-Za-z0-9]+$/, message: "请输入英文字母或数字", trigger: "blur" },
      { max: 20, message: "队列代码不能超过20字符", trigger: "blur" }
    ],
    queueName: [
      { required: true, message: "请输入队列名称", trigger: "blur" },
      { max: 20, message: "队列名称不能超过20字符", trigger: "blur" }
    ],
    queueCategory: [
      { required: true, message: "请选择队列类型", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择队列状态：", trigger: "change" }
    ],
    lockEndDate: [
      { required: true, message: "请选择锁定到期日期", trigger: "change" }
    ],
    divisionStrategyId: [
      { required: true, message: "请选择分案日期策略", trigger: "change" }
    ]
  };

  @Emit("refreshList")
  public refreshList() {}
  @Emit("close")
  public close() {
    this.reset();
  }

  //重置方法
  private reset() {
    this.model.id = "";
    const addForm: any = this.$refs["add-form"];
    addForm.resetFields();
  }

  /**
   * 刷新历史注解数据
   */
  private refreshSignHistoryData() {
    const pageIndex = this.pageSignHistoryService.pageIndex;
    const pageSize = this.pageSignHistoryService.pageSize;
    this.signHistoryPageList = this.signHistoryList.slice(
      (pageIndex - 1) * pageSize,
      pageIndex * pageSize
    );
  }

  private queueIdChange(val) {
    // 队列修改记录 - 详情查看
    if( typeof(val) === 'object' ){
      this.SignHisqueueId = val.queueId
      this.model = val
      this.model.status = "ENABLED"
      this.$nextTick(() => {
        this.model.expireMonth = val.expireMonth;
        this.model.expireDay = val.expireDay;
        this.model.expireDate = this.$filter.dateTimeFormat(val.expireDate);
      });
      this.getQueueSignHisFn()
    } else {
      // 列表查看队列
      if (val === "") return;
      this.queueService.view({ id: val }).subscribe(
        data => {
          this.update(data);
          data.signHistoryList.map(item => {
            item.operatorRealName = item.createName;
            item.createTime = item.timeCreated;
          });
        },
        ({ msg }) => {}
      );
    }

    // 查看/编辑--查询生效的分案日期策略
    this.queueService.queryAllDateStrategy1().subscribe(data => {
      this.strategy = data;
    });
  }

  private getQueueSignHisFn() {
    // 队列修改记录 - 队列历史注记
    this.caseQueueService.getQueueSignHis({ queueId: this.SignHisqueueId }).subscribe(
        data => {
          this.signHistoryPageList = data
          if(!data){ return false }
          data.map(item => {
            item.operatorRealName = item.createName;
            item.createTime = item.timeCreated;
          });
        },
        ({ msg }) => {}
      );
  } 

  /**
   * 反显数据
   */
  private update(data: any) {
    // console.log('111-data',data)
    this.model.id = data.id;
    this.model.queueCode = data.queueCode;
    this.model.queueName = data.queueName;
    this.model.queueCategory = data.queueCategory;
    this.model.status = data.status;
    this.model.divisionStrategyId = data.divisionStrategyId;
    this.model.strategyDate = data.strategyDate;
    this.model.strategyName = data.strategyName;
    this.model.queueRemark = data.queueRemark;
    this.model.lockEndDate = data.lockEndDate;
    this.$nextTick(() => {
      this.model.expireMonth = data.expireMonth;
      this.model.expireDay = data.expireDay;
      this.model.expireDate = this.$filter.dateTimeFormat(data.expireDate);
    });

    this.signHistoryList = data.signHistoryList;
    this.pageSignHistoryService.pageIndex = 1;
    this.pageSignHistoryService.pageSize = 10;
    this.pageSignHistoryService.update({
      totalElements: this.signHistoryList.length,
      totalPages: Math.ceil(
        this.signHistoryList.length / this.pageSignHistoryService.pageSize
      )
    });
    this.refreshSignHistoryData();
  }
  /**
   * 提交验证并并与数据库交互
   */
  private commit() {
    const addForm: any = this.$refs["add-form"];
    addForm.validate(valid => {
      if (valid) {
        const strategy = this.strategy.find(
          item => item.id === this.model.divisionStrategyId
        );
        this.model.strategyDate = strategy ? strategy.operationDate : "";
        this.model.strategyName = strategy ? strategy.strategyName : "";
        if (this.edit) {
          this.editBtn()
        } else {
          this.addBtn()
        }
      }
    });
  }
  private editBtn(){
    this.queueService.update(this.model).subscribe(
      data => {
        this.$message.success("提交审批成功!");
        // 刷新列表
        this.refreshList();
        // 关闭
        this.close();
      },
      ({ msg }) => {}
    );
  }
  private addBtn(){
    this.queueService.add(this.model).subscribe(
      data => {
        this.$message.success("提交审批成功!");
        // 刷新列表
        this.refreshList();
        // 关闭
        this.close();
      },
      ({ msg }) => {}
    );
  }
  /*
   * 获取日历Itme类名
   */
  private getDateClass(index) {
    return {
      calendarItem: true,
      active: this.dateSelect(index+1, this.strategy)
    };
  }
  /**
   * 反显日期策略日期
   */
  private dateSelect(date, strategyList) {
    const strategy = strategyList.find(
      item => item.id === this.model.divisionStrategyId
    );
    let exist = false;
    if (strategy) {
      exist = strategy.operationDate.split(",").some(item => {
        return item === date + "";
      });
    }
    return exist;
  }

  /**
   * 监听锁定到期日期
   */
  @Watch("model.lockEndDate", { immediate: true })
  private lockEndDateOnChange(val) {
    this.model.expireMonth = "";
    this.model.expireDay = "";
    this.model.expireDate = "";
  }
  /**
   * 校验锁定到期日期
   */
  private validateExpireMonth(rule, value, callback) {
    if (!["MONTH_DAY", "MONTH"].includes(this.model.lockEndDate)) {
      callback();
    } else {
      if (/^[1-9][0-9]*$/.test(value)) {
        this.model.expireMonth = Number(value);
        callback();
      } else {
        callback(new Error("请输入正整数"));
      }
    }
  }
  private validateExpireDay(rule, value, callback) {
    if (!["MONTH_DAY", "DAY"].includes(this.model.lockEndDate)) {
      callback();
    } else {
      if (this.model.lockEndDate === "DAY") {
        if (/^[1-9][0-9]*$/.test(value)) {
          this.model.expireDay = Number(value);
          callback();
        } else {
          callback(new Error("请输入正整数"));
        }
      } else {
        //正则匹配1-30
        const reg = /^([12][0-9]|30|[1-9])$/;
        //正则匹配1-31
        // const reg = /^([1-9]|[12][0-9]|30|31)$/
        if (reg.test(value)) {
          this.model.expireDay = Number(value);
          callback();
        } else {
          callback(new Error("请输入1-30的整数"));
        }
      }
    }
  }
  private validateExpireDate(rule, value, callback) {
    if ("SOME" !== this.model.lockEndDate) {
      callback();
    } else {
      if (value) {
        callback();
      } else {
        callback(new Error("日期不能为空"));
      }
    }
  }


  private created() {
    // 新增--查询生效的分案日期策略
    this.queueService.queryAllDateStrategy().subscribe(data => {
      this.strategy = data;
    });
  }
}
</script>

<style lang="less" scoped>
.add-queue-title {
  padding-bottom: 30px;
  padding-left: 30px;
  font-size: 18px;
  font-weight: bold;
}
.agent-box {
  margin-bottom: 22px;
  .text-right {
    text-align: right;
  }
}
.calendar {
  overflow: hidden;
  margin: 0 200px 22px;
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  .calendarItem {
    float: left;
    width: 10%;
    box-sizing: border-box;
    line-height: 20px;
    text-align: center;
    border-bottom: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    &.active {
      background-color: #e4e7ed;
    }
  }
}
.history-table {
  /deep/ .el-pagination .el-select .el-input {
    width: 100px !important;
  }
  /deep/ .el-pagination__editor.el-input {
    width: 50px !important;
  }
}
</style>
